import os
import queue
from datetime import datetime
from time import sleep
from PySide2.QtCore import Signal, Qt
from PySide2.QtWidgets import QFileDialog, QMessageBox, QTreeWidgetItemIterator, QTreeWidgetItem
from src.lib.errorno import g_errno_d
from src.lib.thread_stop import stop_thread

class AppUser():

    rx_buff = queue.Queue()
    m_b_is_LF = 1  # 0--不加\r\n  1--加\r\n
    m_b_writeCfgFlag = 0
    m_b_readCfgFlag = 0
    m_b_LampInfoFlag = 0

    def __init__(self, ui, port):
        self.ui = ui
        self.Port = port
        self.MainWindow = self.ui.MainWindow

    # 投递文本到[调试接收框]
    def uiForwardReceive(self, text):
        self.Port.sendTextToReceive(self.Port.Page['DEBUG'].value, text)

    '''
    读取参数配置
    AT^LAMPCFG?
    '''
    def uiReadConfig(self):
        self.MainWindow.btn_readConfig.setEnabled(False)
        if self.Port.getPortState():
            QMessageBox.critical(self.ui, "Port Error", "请先打开串口！")
            self.MainWindow.btn_readConfig.setEnabled(True)
            self.MainWindow.btn_readConfig.setFocus()
            return
        if self.m_b_readCfgFlag != 0:
            self.MainWindow.btn_readConfig.setEnabled(True)
            return
        self.m_b_readCfgFlag = 1
        input_s = "AT^LAMPCFG?\r\n"
        data = (input_s).encode()
        self.Port.sendMsg(data)
        self.uiForwardReceive(input_s)
        self.m_b_readCfgFlag = 0
        self.MainWindow.btn_readConfig.setEnabled(True)
        self.MainWindow.btn_readConfig.setFocus()

    '''
    写入参数配置
    AT^LAMPCFG=<Mode><Gears><Tpye><Param0><Param1><Param2><Param3><ParamN>
    '''
    def uiWriteConfig(self):
        if self.Port.getPortState():
            QMessageBox.critical(self.ui, "Port Error", "请先打开串口！")
            return
        if self.m_b_writeCfgFlag != 0:
            return
        self.m_b_writeCfgFlag = 1
        temp_list = []
        item = QTreeWidgetItemIterator(self.MainWindow.twd_lightType)
        mode = -1
        level = -1
        while item.value():
            temp = item.value().text(0)
            if temp.find("Mode") != -1:
                mode += 1
                item = item.__iadd__(1)
                level = -1
                continue
            else:
                if temp.find("Gears") != -1:
                    level += 1
            temp_list.append(str(mode) + "-" + str(level) + "-" + item.value().text(1))
            item = item.__iadd__(1)
        print(temp_list)
        input_s = ','.join(temp_list)
        input_s = "AT^LAMPCFG=" + input_s + "\r\n"
        data = (input_s).encode()
        self.Port.sendMsg(data)
        self.uiForwardReceive(input_s)
        self.m_b_writeCfgFlag = 0

    def uiRefreshLampCfg(self, data):
        index = -1
        if len(data) > 0:
            self.MainWindow.twd_lightType.clear()
            for i in range(0, len(data)):
                if data[i] != "":
                    para = data[i].split("-", 2)
                    print(para)
                    if len(para) == 3:
                        if index != para[0]:
                            index = para[0]
                            #设置根节点
                            item = QTreeWidgetItem(self.MainWindow.twd_lightType)
                            item.setText(0, "Mode")
                            print("Add 模式", index)

                        child = QTreeWidgetItem(item)
                        child.setText(0, "Gears")
                        child.setText(1, para[2])
                        child.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEditable|Qt.ItemIsDragEnabled|Qt.ItemIsDropEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsEnabled)
                        self.MainWindow.twd_lightType.addTopLevelItem(item)
            # 节点全部展开
            self.MainWindow.twd_lightType.expandAll()

    '''
    刷新车灯信息
    AT^VERSION? AT^POWERINFO?
    '''
    def uiRefreshLampInfo(self):
        self.MainWindow.btn_refreshLampInfo.setEnabled(False)
        if self.Port.getPortState():
            QMessageBox.critical(self.ui, "Port Error", "请先打开串口！")
            self.MainWindow.btn_refreshLampInfo.setEnabled(True)
            self.MainWindow.btn_refreshLampInfo.setFocus()
            return
        if self.m_b_LampInfoFlag != 0:
            self.MainWindow.btn_refreshLampInfo.setEnabled(True)
            return
        self.m_b_LampInfoFlag = 1

        input_s = "AT^VERSION?\r\n"
        data = (input_s).encode()
        self.Port.sendMsg(data)
        self.uiForwardReceive(input_s)
        sleep(0.05)
        input_s = "AT^POWERINFO?\r\n"
        data = (input_s).encode()
        self.Port.sendMsg(data)
        self.uiForwardReceive(input_s)
        sleep(0.05)
        input_s = "AT^SYSINFO?\r\n"
        data = (input_s).encode()
        self.Port.sendMsg(data)
        self.uiForwardReceive(input_s)
        sleep(0.03)
        input_s = "AT^LAMPPWMOUT?\r\n"
        data = (input_s).encode()
        self.Port.sendMsg(data)
        self.uiForwardReceive(input_s)
        sleep(0.03)
        input_s = "AT^LAMPTEMPERATURE?\r\n"
        data = (input_s).encode()
        self.Port.sendMsg(data)
        self.uiForwardReceive(input_s)

        self.m_b_LampInfoFlag = 0
        self.MainWindow.btn_refreshLampInfo.setEnabled(True)
        self.MainWindow.btn_refreshLampInfo.setFocus()

    def uiLampCfgAddMode(self):
        #设置根节点
        item = QTreeWidgetItem(self.MainWindow.twd_lightType)
        item.setText(0, "Mode")
        print("Add 模式")

        child = QTreeWidgetItem(item)
        child.setText(0, "Gears")
        child.setText(1, "")
        child.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEditable|Qt.ItemIsDragEnabled|Qt.ItemIsDropEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsEnabled)
        self.MainWindow.twd_lightType.addTopLevelItem(item)
        # 节点全部展开
        self.MainWindow.twd_lightType.expandAll()

    def uiLampCfgDeleteMode(self):
        item = self.MainWindow.twd_lightType.currentItem()
        if item != None:
            father_node = item.parent()
            rootIndex = self.MainWindow.twd_lightType.indexOfTopLevelItem(item)
            self.MainWindow.twd_lightType.takeTopLevelItem(rootIndex)

    def uiLampCfgAddGear(self):
        try:
            item = self.MainWindow.twd_lightType.currentItem()
            if item != None:
                father_node = item.parent()
                child = QTreeWidgetItem(father_node)
                child.setText(0, "Gears")
                child.setText(1, "")
                child.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEditable|Qt.ItemIsDragEnabled|Qt.ItemIsDropEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsEnabled)
                self.MainWindow.twd_lightType.addTopLevelItem(father_node)
        except Exception:
            pass

    def uiLampCfgDeleteGear(self):
        try:
            item = self.MainWindow.twd_lightType.currentItem()
            if item != None:
                father_node = item.parent()
                father_node.removeChild(item)
        except Exception:
            pass